#include<iostream>
#include<cstdio>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
class Sem{
  public:
    Sem(int num)
    {
      sem_init(&_sem,0,num);
    }
    ~Sem()
    {
      sem_destroy(&_sem);
    }
    void P()
    {
      sem_wait(&_sem);
    }
    void V()
    {
      sem_post(&_sem);
    }
private:
    sem_t _sem;
};

Sem sem(1);//二元信号量

int tickets = 1000;

void* TicketFun(void* arg)
{
  char* msg = (char*)arg;
  while(1)
  {
    sem.P();
    if(tickets>0)
    {
      usleep(1000);
      printf("%s get a ticket...,剩余：%d\n",msg,--tickets);
      sem.V();
    }
    else 
    {
      sem.V();
      break;
    }
  }
  printf("%s quit...\n",msg);
  pthread_exit((void*)0);
}

int main()
{
  pthread_t t1,t2,t3,t4;
  pthread_create(&t1, nullptr,TicketFun,(void*)"thread 1");
  pthread_create(&t2, nullptr,TicketFun,(void*)"thread 2");
  pthread_create(&t3, nullptr,TicketFun,(void*)"thread 3");
  pthread_create(&t4, nullptr,TicketFun,(void*)"thread 4");

  pthread_join(t1,nullptr);
  pthread_join(t3,nullptr);
  pthread_join(t4,nullptr);
  pthread_join(t2,nullptr);
  return 0;
}
